package com.mrjy.coursepackage.bo;


import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mrjy.common.entity.CoursePackageInfo;
import com.mrjy.common.entity.CoursePackageVideoRel;
import com.mrjy.common.entity.CoursePackageVip;
import com.mrjy.common.entity.CoursepackageVideoTypeRel;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserMemberInfo;
import com.mrjy.common.entity.VideoInfo;
import com.mrjy.common.enums.ResultEnum;
import com.mrjy.common.redis.RedisPool;
import com.mrjy.common.solr.SolrServerClient;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.common.util.RegexUtil;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.common.util.SolrUtil;
import com.mrjy.coursepackage.dao.ICoursePackageInfoDao;
import com.mrjy.coursepackage.dao.ICoursePackageVideoRelDao;
import com.mrjy.coursepackage.dao.ICoursePackageVipDao;
import com.mrjy.coursepackage.dao.ICoursepackageVideoTypeRelDao;
import com.mrjy.coursepackage.dao.IUserCoursePackageDao;
import com.mrjy.coursepackage.dto.CoursePackageInfoDTO;
import com.mrjy.coursepackage.dto.CoursePackageVideoRelDTO;
import com.mrjy.coursepackage.dto.CoursePackageVideoTypeDTO;
import com.mrjy.coursepackage.dto.CoursePackageVipDTO;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.maintain.util.SharingProportionEnum;
import com.mrjy.queries.dto.CourseDTO;
import com.mrjy.queries.dto.RelatedCourseDTO;
import com.mrjy.share.dao.IOperationCenterInfoDao;
import com.mrjy.share.dao.IPromotorLinkDao;
import com.mrjy.share.dto.PromotorLinkDTO;
import com.mrjy.video.dao.IVideoInfoDao;
import com.mrjy.wechat.conts.WxConsts;

@Service("coursePackageInfoBo")
public class CoursePackageInfoBo implements ICoursePackageInfoBo {

	@Resource
	private ICoursePackageInfoDao coursePackageInfoDao;
	@Resource
	private IUserMemberInfoDao userMemberInfoDao;
	@Resource
	private ICoursepackageVideoTypeRelDao coursepackageVideoTypeRelDao;
	@Resource
	private ICoursePackageVideoRelDao coursePackageVideoRelDao;
	@Resource
	private ICoursePackageVipDao coursePackageVipDao;
	@Resource
	private IUserInfoDao userInfoDao;
	@Autowired
	private SolrServerClient solrServerClient;
	@Autowired
	private IVideoInfoDao videoInfoDao;
	@Autowired
	private RedisPool redisPool;
    @Resource
    private IUserCoursePackageDao userCoursePackageDao;
    
    @Resource
    private IPromotorLinkDao promotorLinkDao;
    
    
    private Logger LOGGER = LoggerFactory.getLogger(CoursePackageInfoBo.class);


    /* (non-Javadoc)
     * @see com.mrjy.coursepackage.bo.ICoursePackageInfoBo#txInsert(com.mrjy.coursepackage.dto.CoursePackageInfoDTO, javax.servlet.http.HttpSession)
     */
    @Override
	public Object txInsert(CoursePackageInfoDTO info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		//数据校验
		if (StringUtils.isBlank(info.getCoursePackageName())) {
			map.put("err_code", 400);
			map.put("err_msg", "课程包名称不能为空");
			return map;
		}
		if (info.getCoursePackageName().length()>50) {
			map.put("err_code", 401);
			map.put("err_msg", "课程包名称不能超过50个字符");
			return map;
		}
		if (StringUtils.isBlank(info.getCoverUrl())) {
			map.put("err_code", 402);
			map.put("err_msg", "课程包封面不能为空");
			return map;
		}
		if (StringUtils.isBlank(info.getCoverUrl())) {
			map.put("err_code", 402);
			map.put("err_msg", "课程包封面不能为空");
			return map;
		}
		/*if (info.getStageTabId()==null) {
			map.put("err_code", 409);
			map.put("err_msg", "课程包阶段不能为空");
			return map;
		}*/
		if (info.getTypeIds()==null||info.getTypeIds().size()==0) {
			map.put("err_code", 403);
			map.put("err_msg", "课程包标签不能为空");
			return map;
		}
		if (info.getTypeIds().size()>10) {
			map.put("err_code", 404);
			map.put("err_msg", "课程包标签不能超过10个");
			return map;
		}
		if (info.getOriginalPrice()==null
				||!RegexUtil.checkDecimals(info.getOriginalPrice()+"")) {
			map.put("err_code", 405);
			map.put("err_msg", "请正确填写原价(必须为大于等于0的数值)");
			return map;
		}
		if (info.getDiscountPrice()==null
				||!RegexUtil.checkDecimals(info.getOriginalPrice()+"")) {
			map.put("err_code", 406);
			map.put("err_msg", "请正确填写折扣价(必须为大于等于0的数值)");
			return map;
		}
		if (info.getTotalCourseNum()==null
				||!RegexUtil.checkDigit(info.getTotalCourseNum()+"")) {
			map.put("err_code", 407);
			map.put("err_msg", "请正确填写预更新微课数(必须为大于0的整数)");
			return map;
		}
		if (info.getVideoIds()==null||info.getVideoIds().size()==0) {
			map.put("err_code", 408);
			map.put("err_msg", "请添加视频");
			return map;
		}
		if (StringUtils.isBlank(info.getIsSpecial())) {
			map.put("err_code", 409);
			map.put("err_msg", "请选择课程包类型");
			return map;
		}
		VideoInfo video = new VideoInfo();
		List<Integer> vids = info.getVideoIds();
		//判断选择的微课里，是否含有特价微课
		if (info.getIsSpecial().equals("1")) {
			int count = 0;
			//Integer userId = null;
			for (Integer vid : info.getVideoIds()) {
				video.setId(vid);
				video.setIsSpecial("1");
				int row = videoInfoDao.checkVideoIsSpecial(video);
				if (row>0) {
					count ++;
				}
			}
			if (count == 0) {//说明选择的微课里面没有特价微课
				map.put("err_code", 410);
				map.put("err_msg", "必须至少含有一节特价微课");
				return map;
			}
			
//			for (int i = 0; i < vids.size(); i++) {
//				video = (VideoInfo) videoInfoDao.queryById(vids.get(i));
//				if (i >= 1 && userId.intValue() != video.getUserId().intValue()) {
//					map.put("err_code", 411);
//					map.put("err_msg", "特价课程包只能包含一位讲师的课");
//					return map;
//				}
//				userId = video.getUserId();
//			}
//			info.setUserId(userId);
		}else if ("0".equals(info.getIsSpecial())) {
			for (Integer vid : vids) {
				video = (VideoInfo) videoInfoDao.queryById(vid);
				if ("1".equals(video.getIsSpecial())) {
					map.put("err_code", 412);
					map.put("err_msg", "VIP课程包不能含有特价微课");
					return map;
				}
			}
		}
		info.setDisableFlag(0);
		info.setClickCount(0);
		info.setCreateTime(new Timestamp(System.currentTimeMillis()));
		info.setCoursePackageType(1);//默认主题课程包
		info.setAnnouncementFlag(1);//默认未通知
		int count = coursePackageInfoDao.insert(info);
		if (count > 0 ) {
			try{
				if(null != info.getTypeIds() && info.getTypeIds().size() >0){
					//插入标签
					int resultInsertTypeId = insertByTypeIds(info.getTypeIds(), info.getId());
					if(resultInsertTypeId != info.getTypeIds().size()){
						map.put("err_code", 4001);
						map.put("err_msg", "标签插入失败，插入条数：" + resultInsertTypeId);
					}
				}
				
				//批量添加视频
				String teacherName = "";
				if(null != info.getVideoIds() && info.getVideoIds().size() >0){
					int resultInsertVideoId = insertByVideoIds(info.getVideoIds(), info.getId());
					if(resultInsertVideoId != info.getVideoIds().size()){ 
						map.put("err_code", 4002);
						map.put("err_msg", "视频插入失败，插入条数：" + resultInsertVideoId);
					}
					for (Integer videoId : info.getVideoIds()) {
						video = (VideoInfo) videoInfoDao.queryById(videoId);
						if (!teacherName.contains(video.getUserName())) {
							teacherName += video.getUserName()+",";
						}
					}
					teacherName = teacherName.substring(0, teacherName.length()-1);
				}
				//添加索引
				SolrEntity entity = new SolrEntity();
				entity.setId("coursePackage_"+info.getId());
				entity.setCoursePackageId(info.getId());
				entity.setCoursePackageName(info.getCoursePackageName());
				entity.setCoursePackageDesc(info.getCoursePackageDesc());
				entity.setCoursePackageTypes(SolrUtil.formatVideoTypes(info.getTypeIds().toArray(new Integer[info.getTypeIds().size()])));
				entity.setCoursePackageTeacher(teacherName);
				entity.setCoverUrl(info.getCoverUrl());
				solrServerClient.add(entity);
	    		map.put("solr_msg", "索引插入成功");
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    		LOGGER.debug("[索引插入失败]："+e.getMessage());
	    		map.put("solr_msg", "索引插入失败");
	    		map.put("err_code", 500);
	    		map.put("err_msg", "插入失败");
	    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    		return map;
	    	}
			map.put("err_code", 200);
			map.put("err_msg", "插入成功");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "插入失败");
		}
		return map;
	}

	@Override
	public Object txUpdate(CoursePackageInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count = coursePackageInfoDao.update(info);
		if (count > 0 ) {
			map.put("err_code", 0);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

	@Override
	public Object txUpdateById(CoursePackageInfoDTO info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if(null == info){
			map.put("err_code", -1);
			map.put("err_msg", "更新信息为空");
			return map;
		}
		//数据校验
		if (StringUtils.isBlank(info.getCoursePackageName())) {
			map.put("err_code", 400);
			map.put("err_msg", "课程包名称不能为空");
			return map;
		}
		if (info.getCoursePackageName().length()>50) {
			map.put("err_code", 401);
			map.put("err_msg", "课程包名称不能超过50个字符");
			return map;
		}
		if (StringUtils.isBlank(info.getCoverUrl())) {
			map.put("err_code", 402);
			map.put("err_msg", "课程包封面不能为空");
			return map;
		}
		if (StringUtils.isBlank(info.getCoverUrl())) {
			map.put("err_code", 402);
			map.put("err_msg", "课程包封面不能为空");
			return map;
		}
		/*if (info.getStageTabId()==null) {
			map.put("err_code", 409);
			map.put("err_msg", "课程包阶段不能为空");
			return map;
		}*/
		if (info.getTypeIds()==null||info.getTypeIds().size()==0) {
			map.put("err_code", 403);
			map.put("err_msg", "课程包标签不能为空");
			return map;
		}
		if (info.getTypeIds().size()>10) {
			map.put("err_code", 404);
			map.put("err_msg", "课程包标签不能超过10个");
			return map;
		}
		if (info.getOriginalPrice()==null
				||!RegexUtil.checkDecimals(info.getOriginalPrice()+"")) {
			map.put("err_code", 405);
			map.put("err_msg", "请正确填写原价(必须为大于等于0的数值)");
			return map;
		}
		if (info.getDiscountPrice()==null
				||!RegexUtil.checkDecimals(info.getOriginalPrice()+"")) {
			map.put("err_code", 406);
			map.put("err_msg", "请正确填写折扣价(必须为大于等于0的数值)");
			return map;
		}
		if (info.getTotalCourseNum()==null
				||!RegexUtil.checkDigit(info.getTotalCourseNum()+"")) {
			map.put("err_code", 407);
			map.put("err_msg", "请正确填写预更新微课数(必须为大于0的整数)");
			return map;
		}
		if (info.getVideoIds()==null||info.getVideoIds().size()==0) {
			map.put("err_code", 408);
			map.put("err_msg", "请添加视频");
			return map;
		}
		if (StringUtils.isBlank(info.getIsSpecial())) {
			map.put("err_code", 409);
			map.put("err_msg", "请选择课程包类型");
			return map;
		}
		VideoInfo video = new VideoInfo();
		//判断选择的微课里，是否含有特价微课
		List<Integer> _vids = info.getVideoIds();
		if (info.getIsSpecial().equals("1")) {
			int count = 0;
			//Integer userId = null;
			for (Integer vid : info.getVideoIds()) {
				video.setId(vid);
				video.setIsSpecial("1");
				int row = videoInfoDao.checkVideoIsSpecial(video);
				if (row>0) {
					count ++;
				}
			}
			if (count == 0) {//说明选择的微课里面没有特价微课
				map.put("err_code", 410);
				map.put("err_msg", "必须至少含有一节特价微课");
				return map;
			}
//			for (int i = 0; i < _vids.size(); i++) {
//				video = (VideoInfo) videoInfoDao.queryById(_vids.get(i));
//				if (i >= 1 && userId.intValue() != video.getUserId().intValue()) {
//					map.put("err_code", 411);
//					map.put("err_msg", "特价课程包只能包含一位讲师的课");
//					return map;
//				}
//				userId = video.getUserId();
//			}
//			info.setUserId(userId);
		}else if ("0".equals(info.getIsSpecial())) {
			for (Integer vid : _vids) {
				video = (VideoInfo) videoInfoDao.queryById(vid);
				if ("1".equals(video.getIsSpecial())) {
					map.put("err_code", 412);
					map.put("err_msg", "VIP课程包不能含有特价微课");
					return map;
				}
			}
		}
		/*if(info.getCoursePackageType() == 1){//主题课程包
			info.setUserId(0);//把导师id清空
		}
		*/

        CoursePackageInfoDTO _coursePackage = coursePackageInfoDao.selectById(info);
        String[] _arr = _coursePackage.getVideoIdsString().split(",");
        List<Integer> _videoIds = new ArrayList<>();
		for (String string : _arr) {
			_videoIds.add(Integer.parseInt(string));
		}
		
		if (!ArrayUtils.isEquals(info.getVideoIds(), _videoIds)) {
			//课程包中微课有更新，设置更新时间和通知状态
			info.setUpdateTime(new Timestamp(System.currentTimeMillis()));
			info.setAnnouncementFlag(1);
		}
        int count = coursePackageInfoDao.updateById(info);
        if (count > 0) {
            //判断课程包里的视频是否有变动
			//如果有变动，则需要相应的更新redis中的USER_VIDEO_VIP
			if (!ArrayUtils.isEquals(info.getVideoIds(), _videoIds)) {
				//查出谁购买了这个课程包
				CoursePackageVip vip = new CoursePackageVip();
				vip.setCoursePackageId(info.getId());
				List<CoursePackageVipDTO> payUsers = coursePackageVipDao.queryWhoPayByCoursePackageId(vip);
				//去redis中找出这些人的记录，把（修改之前的）vids移除，重新追加新的vids
				for (CoursePackageVip payUser : payUsers) {
					String vids = redisPool.get(GlobalConstant.USER_VIDEO_VIP+payUser.getUserId());
					//移除
					for (String _vid : _arr) {
						if(StringUtils.isNotBlank(vids)) {
							vids = vids.replace(_vid+",", "");	
						}
						
					}
					//追加
					for (Integer vid : info.getVideoIds()) {
						vids += (vid+",");
					}
					redisPool.set(GlobalConstant.USER_VIDEO_VIP+payUser.getUserId(), vids);
				}
			}

            try {
                //删除标签关联，后插入标签关联
                if(null != info.getTypeIds() && info.getTypeIds().size() > 0){
					int result = coursepackageVideoTypeRelDao.deleteByCoursepkId(info.getId());
					int returnCount = insertByTypeIds(info.getTypeIds(), info.getId());
					if(info.getTypeIds().size() != returnCount){
						map.put("err_code", 4001);
						map.put("err_msg", "标签添加关联不成功，添加条数为："+returnCount);
					}
				}
				//先插入视频相关，后插入视频相关
				String teacherName = "";
				if(null != info.getVideoIds() && info.getVideoIds().size() > 0){
					int result = coursePackageVideoRelDao.deleteByCoursepkId(info.getId());
					int returnCount = insertByVideoIds(info.getVideoIds(), info.getId());
					if(info.getVideoIds().size() != returnCount){
						map.put("err_code", 4002);
						map.put("err_msg", "视频添加关联不成功，添加条数为："+returnCount);
					}
					for (Integer videoId : info.getVideoIds()) {
						video = (VideoInfo) videoInfoDao.queryById(videoId);
						if (!teacherName.contains(video.getUserName())) {
							teacherName += video.getUserName()+",";
						}
					}
					teacherName = teacherName.substring(0, teacherName.length()-1);
				} 
				//更新索引
				SolrInputDocument document = new SolrInputDocument();
	    		document.addField("id", "coursePackage_"+info.getId());
	    		document.addField("coursePackageId", info.getId());
	    		document.addField("coursePackageName", info.getCoursePackageName());
	    		document.addField("coursePackageDesc", info.getCoursePackageDesc());
	    		document.addField("coursePackageTypes", SolrUtil.formatVideoTypes(info.getTypeIds().toArray(new Integer[info.getTypeIds().size()])));
	    		document.addField("coursePackageTeacher", teacherName);
	    		document.addField("coverUrl", info.getCoverUrl());
	    		solrServerClient.addDoc(document);
	    		map.put("solr_msg", "索引更新成功");
	    	} catch (Exception e) {
	    		e.printStackTrace();
	    		LOGGER.debug("[索引插入失败]："+e.getMessage());
	    		map.put("solr_msg", "索引更新失败");
	    		map.put("err_code", 500);
	    		map.put("err_msg", "更新失败");
	    		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
	    		return map;
	    	}
			map.put("err_code", 200);
			map.put("err_msg", "更新成功");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "更新失败");
		}
		return map;
	}

	@Override
	public Object txDelete(Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		int count =  coursePackageInfoDao.delete(id);
		if (count > 0 ) {
			map.put("err_code", 0);
			map.put("err_msg", "删除成功");
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "删除失败");
		}
		return map;
	}

	@Override
	public Object selectById(Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		CoursePackageInfoDTO vo = new CoursePackageInfoDTO();
		vo.setId(id);
		CoursePackageInfo info =  coursePackageInfoDao.selectById(vo);
		if ( null != info ) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", info);

            List<CoursePackageVideoRelDTO> videoRellist = coursePackageVideoRelDao.selectByCoursePackageId(info.getId(), null);
            if(null != videoRellist && videoRellist.size() > 0){
				map.put("videoRel", videoRellist);
			}
			List<CoursePackageVideoTypeDTO> videoTypeList = coursepackageVideoTypeRelDao.selectByCoursePackageId(info.getId());
			if(null != videoTypeList && videoTypeList.size() > 0){
				map.put("VideoType", videoTypeList);
			}
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("info", info);
		}
		return map;
	}
    
	@Override
	public Object selectTeacherPackageByIdAndType(CoursePackageInfo packageInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(packageInfo == null){
			map.put("err_code", -1);
			map.put("err_msg", "id不能为空");
			return map;
		}
		CoursePackageInfoDTO dto = coursePackageInfoDao.selectTeacherPackageByIdAndType(packageInfo);

        List<CoursePackageInfoDTO> list = coursePackageInfoDao.selectVideoListById(packageInfo);

        if (list != null && list.size() > 0) {
            dto.setVideoId(list.get(0).getVideoId());
            map.put("videoId", list.get(0).getVideoId());
        }
        if ( null != dto ) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", dto);
            if (dto.getRecommendNum() < 5) {
                dto.setAverageStart(new BigDecimal(9.5));
            }
        }else {
			map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("info", dto);
		}
		return map;
	}

	@Override
    public Object selectThemePackageByIdAndType(CoursePackageInfo info, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
		if(info == null){
			map.put("err_code", -1);
			map.put("err_msg", "id不能为空");
			return map;
		}
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
            map.put("err_code", -1);
            map.put("err_msg", "用户未登录");
            return map;
        }
        info.setUserId(loginUser.getId());

        CoursePackageInfoDTO coursePackageInfoDTO = coursePackageInfoDao.selectVideoInfoByUserId(info);
        CoursePackageInfoDTO dto =  coursePackageInfoDao.selectThemePackageByIdAndType(info);

        List<UserInfo> userPics = coursePackageInfoDao.queryCourseUser(info.getId());
        
        
        //如果是运营中心推广关系，读取运营配置的分成比例 TODO
       PromotorLinkDTO plDTO =  promotorLinkDao.selectOperationCenterByUserId(info.getUserId());
       if(null != plDTO && "1".equals(plDTO.getIsOperation())){
    	   //一级推广，获取一级分成比例
    	   if("1".equals(plDTO.getLevel())){
    		   dto.setSharingProportion(plDTO.getFirstProportions());
    	   }else if("2".equals(plDTO.getLevel())){
    		   //二级推广，获取二级分成比例
    		   dto.setSharingProportion(plDTO.getSecondProportions());
    	   }
       }

        if ("1".equals(dto.getIsSpecial())) {
        	//new BigDecimal(teamDTO.getTeamSharingProportion())).setScale(2, BigDecimal.ROUND_HALF_UP);
			dto.setProfit(new BigDecimal(dto.getDiscountPrice()*SharingProportionEnum.NORMAL.getSharingProportion()).setScale(2, BigDecimal.ROUND_HALF_UP));
		}else if ("0".equals(dto.getIsSpecial())) {
			dto.setProfit(null==dto.getSharingProportion()?
					new BigDecimal(dto.getDiscountPrice()*SharingProportionEnum.NORMAL.getSharingProportion()).setScale(2, BigDecimal.ROUND_HALF_UP)
					:new BigDecimal(dto.getDiscountPrice()*dto.getSharingProportion()).setScale(2, BigDecimal.ROUND_HALF_UP));
		}

        if (coursePackageInfoDTO != null && coursePackageInfoDTO.getIsFinish().equals(1)) {
            //这一集用户看完了
            List<CoursePackageInfoDTO> list = coursePackageInfoDao.selectVideoListById(info);

            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    //如果是最后一集了，那么让他从头看
                    dto.setVideoId(list.get(0).getVideoId());
                    map.put("videoId", list.get(0).getVideoId());
                } else {
                    //如果不是最后一集，那么看下一集
                    if (coursePackageInfoDTO.getVideoId().equals(list.get(i).getVideoId())) {
                        dto.setVideoId(list.get(i + 1).getVideoId());
                        map.put("videoId", list.get(i + 1).getVideoId());

                        break;
                    }
                }
            }
        } else if (coursePackageInfoDTO != null && coursePackageInfoDTO.getIsFinish().equals(0)) {
            //用户没看完，让用户继续看这个视频
            dto.setVideoId(coursePackageInfoDTO.getVideoId());
            map.put("videoId", coursePackageInfoDTO.getVideoId());
        } else {
            //用户没看过这系列的视频
            List<CoursePackageInfoDTO> list = coursePackageInfoDao.selectVideoListById(info);

            if (list != null && list.size() > 0) {
                dto.setVideoId(list.get(0).getVideoId());
                map.put("videoId", list.get(0).getVideoId());
            }
        }

        UserInfo userInfo = userInfoDao.querySimpleInfoById(loginUser.getId());
        map.put("userInfo", userInfo);
        if ( null != dto ) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("info", dto);
            map.put("userPics", userPics);
            if (dto.getRecommendNum() < 5) {
                dto.setAverageStart(new BigDecimal(9.5));
            }
        } else {
            map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("info", dto);
		}
		return map;
	}

	@Override
	public Object selectVideoTypeById(Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<CoursePackageInfoDTO> list =   coursePackageInfoDao.selectVideoTypeById(id);
		if ( null != list ) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("rows", list);
		}
		return map;
	}

	@Override
	public Object selectTeacherHeadImgById(Integer id) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<CoursePackageInfoDTO> list =   coursePackageInfoDao.selectTeacherHeadImgById(id);
		if ( null != list ) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("rows", list);
		}
		return map;
	}

	@Override
	public Object selectMyCoursePackageByUserId(CoursePackageInfo info) {
		Map<String, Object> map = new HashMap<String, Object>();
		//通过用户id查询其是否为会员
		UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(info.getUserId());
		List<CoursePackageInfoDTO> list = null;
		if(null == userMemberInfo){  //非会员
			map.put("vipflag", 0);
			// 通过用户id查询其购买的课程包，根据查看过的视频的课程包排序
			list = coursePackageInfoDao.selectNoVipMyCoursePackageByUserId(info);
            int count = coursePackageInfoDao.selectCountNoVipMyCoursePackageByUserId(info.getUserId());
            /*
             * //通过当前用户的id查询用户最近所看视频属于的课程包
			 * List<CoursePackageInfoDTO> videolist = coursePackageInfoDao.selectVipMyCoursePackageByUserId(info);
			 * */
			if(null != list && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功，有数据");
				map.put("rows", list);
                map.put("count", count);
            } else {
                map.put("err_code", 1);
				map.put("err_msg", "查询成功，无数据");
				//map.put("rows", list);
				map.put("rows",list);
			}
		}else{//会员
			map.put("vipflag", 1);
			list = coursePackageInfoDao.selectVipMyCoursePackageByUserId(info);
            int count = coursePackageInfoDao.selectCountNoVipMyCoursePackageByUserId(info.getUserId());
            if (null != list && list.size() > 0) {
                List<CoursePackageInfoDTO> resultList = new ArrayList<CoursePackageInfoDTO>();
				for(CoursePackageInfoDTO dto : list){
					dto.setExpireTime(DateUtil.dateToString(new Date(userMemberInfo.getEndDate()), 2));//有效期为会员的有效期
					resultList.add(dto);
				}
				map.put("err_code", 0);
				map.put("err_msg", "查询成功，有数据");
				map.put("rows", resultList);
                map.put("count", count);
            } else {
                map.put("err_code", 1);
				map.put("err_msg", "查询成功，无数据");
				map.put("rows", list);
			}
		}
		
		return map;
	}
 
	@Override
	public Object selectPageByCoursePackageType(CoursePackageInfo info,Integer userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(null == userId){
			map.put("err_code", -1);
            map.put("err_msg", "当前用户ID为空");
            return map;
        }
		
		List<CoursePackageInfoDTO> list = coursePackageInfoDao.selectPageByCoursePackageType(info);
		
		if(null != list && list.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功,有数据");
			UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userId);
			if(userMemberInfo != null){
				for (CoursePackageInfoDTO coursePackageInfoDTO : list) {
					coursePackageInfoDTO.setIsVipStatus(true);
				}
			}else{
				CoursePackageVip coursePackageVip = new CoursePackageVip();
				coursePackageVip.setUserId(userId);
				coursePackageVip.setIsVipStatus(1);
				coursePackageVip.setDisableFlag(0);
				for (CoursePackageInfoDTO coursePackageInfoDTO : list) {
					coursePackageVip.setCoursePackageId(coursePackageInfoDTO.getId());
					List<CoursePackageVip> coursePackageVips = coursePackageVipDao.isCoursePackageVip(coursePackageVip);
					if(coursePackageVips !=null && coursePackageVips.size() > 0){
						coursePackageInfoDTO.setIsVipStatus(true);
					}else{
						coursePackageInfoDTO.setIsVipStatus(false);
					}
				}
			}
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询成功，无数据");
			map.put("rows", list);
		}
		return map;
	}

	@Override
    public Object selectVideoListById(CoursePackageInfo info, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
            map.put("err_code", -1);
            map.put("err_msg", "用户未登录");
            return map;
        }
        info.setUserId(loginUser.getId());
        List<CoursePackageInfoDTO> list = coursePackageInfoDao.selectVideoListById(info);

        for (CoursePackageInfoDTO coursePackageInfoDTO : list) {
            //MP3
            if (StringUtils.isNotBlank(coursePackageInfoDTO.getAudioCode())) {
                PolyInfo cache = RedisUtil.cache(coursePackageInfoDTO.getVideoId() + "");
                coursePackageInfoDTO.setMp3(cache.getMp3());
            }

            //会员那层免费的，后端不判断
            if (coursePackageInfoDTO.getFreeFlag() == 0) {
                Boolean videoVip = RedisUtil.isVideoVip(info.getUserId(), coursePackageInfoDTO.getVideoId());
                if (videoVip) {
                    coursePackageInfoDTO.setIsVipStatus(true);
                } else {
                    coursePackageInfoDTO.setIsVipStatus(false);
                }
            } else {
                coursePackageInfoDTO.setIsVipStatus(false);
            }
            
            //【视频免费规则1】七天免费看视频
            //【服务站特定规则1:指定的课程包不参与7天免费活动】
            long currentTimeStr = new Date().getTime();
            if(!info.getId().equals(83) &&  null != loginUser.getRegisterDate() && ((currentTimeStr - loginUser.getRegisterDate()) / (60 *60 *24 *1000)) <= 7){
            	coursePackageInfoDTO.setIsVipStatus(true);
            }
            
            
          //【视频免费规则2】活动期间免费
            if("true".equals(WxConsts.IS_VIP_STATUS)){
            	coursePackageInfoDTO.setIsVipStatus(true);
            }
            
        }

		if(null != list && list.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "查询成功,有数据");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询成功，无数据");
			map.put("rows", list);
		}
		return map;
	}

	@Override
	public Object txDeleteByIds(int[] ids) {
		try {
			return coursePackageInfoDao.deleteByIds(ids);
		} catch (DataAccessException e) {
			return 0;
		}
	}

	@Override
	public Object txUpdateDisableFlag(CoursePackageInfo info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		int row = coursePackageInfoDao.updateDisableFlag(info);
		if (row>0) {
			if (info.getDisableFlag().intValue() == 0) {
				//数据库启用,添加索引
				try {
					for (Integer id : info.getIds()) {
						SolrEntity coursePackageEntity = new SolrEntity();
						CoursePackageInfoDTO coursePackage = new CoursePackageInfoDTO() ;
						coursePackage.setId(id);
						coursePackage = coursePackageInfoDao.selectById(coursePackage);
						coursePackageEntity.setId("coursePackage_"+id);
						coursePackageEntity.setCoursePackageId(id);
						coursePackageEntity.setCoursePackageName(coursePackage.getCoursePackageName());
						coursePackageEntity.setCoursePackageDesc(coursePackage.getCoursePackageDesc());
						coursePackageEntity.setCoursePackageTypes(coursePackage.getTypeName());
						coursePackageEntity.setCoursePackageTeacher(coursePackage.getUserName());
						coursePackageEntity.setCoverUrl(coursePackage.getCoverUrl());
	                	solrServerClient.add(coursePackageEntity);
					}
					map.put("solr_msg", "索引添加成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引添加失败]："+e.getMessage());
					map.put("solr_msg", "索引添加失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}else if (info.getDisableFlag().intValue() == 1) {
				//数据库禁用,要删除索引
				try {
					for (Integer id : info.getIds()) {
						solrServerClient.deleteById("coursePackage_"+id);
					}
					map.put("solr_msg", "索引删除成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引删除失败]："+e.getMessage());
					map.put("solr_msg", "索引删除失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}
			map.put("err_code", 200);
			map.put("err_msg", "操作成功,"+row+"条记录受影响");
		}else {
			map.put("err_code", 500);
			map.put("err_msg", "操作失败,"+row+"条记录受影响");
		}
		return map;
	}

	@Override
	public Object selectCoursePackageByIdAndType(CoursePackageInfo packageInfo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(packageInfo == null){
			map.put("err_code", -1);
			map.put("err_msg", "id不能为空");
			return map;
		}
		CoursePackageInfoDTO dto  = null;
		if(packageInfo.getCoursePackageType() == 1){//主题课程包
			dto = coursePackageInfoDao.selectThemePackageByIdAndType(packageInfo);
		}else if(packageInfo.getCoursePackageType() == 2){//导师课程包
			dto = coursePackageInfoDao.selectTeacherPackageByIdAndType(packageInfo);
		}
		if ( null != dto ) {
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", dto);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询失败");
			map.put("info", dto);
		}
		return map;
	}

	@Override
	public Object selectPageByCoursePackageTypeForBack(CoursePackageInfoDTO info,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		//数据校验
		if (StringUtils.isNotBlank(info.getCoursePackageName())) {
			info.setCoursePackageName(info.getCoursePackageName());
		}
		//查询全站课程包数
		int total =  coursePackageInfoDao.selectCountByCoursePackageTypeForBack(info);
		List<CoursePackageInfoDTO> list = new ArrayList<CoursePackageInfoDTO>();
		if(total > 0){
			list = coursePackageInfoDao.selectPageByCoursePackageTypeForBack(info);
			map.put("err_code", 0);
			map.put("err_msg", "查询成功,有数据");
			map.put("rows", list);
			map.put("total", total);
            map.put("totalCount", total);
        }else {
			map.put("err_code", 1);
			map.put("err_msg", "查询成功，无数据");
			map.put("rows", list);
			map.put("total", total);
            map.put("totalCount", total);
        }
		return map;
	}

	@Override
    public Object queryAllTeacherPackage(Integer teacherId, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
            map.put("err_code", -1);
            map.put("err_msg", "用户未登录");
            return map;
        }

        CoursePackageInfo coursePackageInfo = new CoursePackageInfo();
        coursePackageInfo.setUserId(teacherId);
        List<CoursePackageInfoDTO> teacherlist = coursePackageInfoDao.queryAllTeacherPackage(coursePackageInfo);
        if(null != teacherlist && teacherlist.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "导师包查询成功,有数据");

            UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(loginUser.getId());
            if(userMemberInfo != null){
				for (CoursePackageInfoDTO coursePackageInfoDTO : teacherlist) {
					coursePackageInfoDTO.setIsVipStatus(true);
				}
			}else{
				CoursePackageVip coursePackageVip = new CoursePackageVip();
                coursePackageVip.setUserId(loginUser.getId());
                coursePackageVip.setIsVipStatus(1);
				coursePackageVip.setDisableFlag(0);
				for (CoursePackageInfoDTO coursePackageInfoDTO : teacherlist) {
					coursePackageVip.setCoursePackageId(coursePackageInfoDTO.getId());
					List<CoursePackageVip> coursePackageVips = coursePackageVipDao.isCoursePackageVip(coursePackageVip);
					if(coursePackageVips !=null && coursePackageVips.size() > 0){
						coursePackageInfoDTO.setIsVipStatus(true);
					}else{
						coursePackageInfoDTO.setIsVipStatus(false);
					}
				}
			}
			map.put("rows", teacherlist);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "导师包查询失败，无数据");
			map.put("rows",null);
		}
		return map;
	}
	
	@Override
	public Object queryTeacherPackageByUserId(Integer teacherId) {
		return coursePackageInfoDao.queryMSPackageByTeacherId(teacherId);
	}

	@Override
	public Object queryAllThemePackage(Integer teacherId,Integer userId) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<String, Object>();
		List<CoursePackageInfoDTO> themelist = coursePackageInfoDao.queryAllThemePackage(teacherId);
		
		if(null != themelist && themelist.size() > 0){
			map.put("err_code", 0);
			map.put("err_msg", "主题包查询成功,有数据");
			CoursePackageVip coursePackageVip = null;
			UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userId);
			for(CoursePackageInfoDTO coursePackageInfoDTO : themelist){
				if(null != userMemberInfo){//会员
					coursePackageInfoDTO.setIsVipStatus(true);
				}else{
					coursePackageInfoDTO.setIsVipStatus(false);
				}
				if("1".equals(coursePackageInfoDTO.getIsSpecial())){//特价
					coursePackageVip = new CoursePackageVip();
					coursePackageVip.setUserId(userId);
					coursePackageVip.setIsVipStatus(1);
					coursePackageVip.setDisableFlag(0);
					coursePackageVip.setCoursePackageId(coursePackageInfoDTO.getId());
					List<CoursePackageVip> coursePackageVips = coursePackageVipDao.isCoursePackageVip(coursePackageVip);
					if(null == coursePackageVips){
						coursePackageInfoDTO.setIsVipStatus(false);
					}
				}
			}
			map.put("rows", themelist);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "主题包查询失败，无数据");
			map.put("rows",null);
		}
		return map;
	}
	
	public int insertByTypeIds(List<Integer> typeIds,int coursepackageId){
		int count = 0;
		for (Integer i : typeIds) {
			CoursepackageVideoTypeRel rel = new CoursepackageVideoTypeRel();
			rel.setVideoTypeId(i);
			rel.setCoursepackageId(coursepackageId);
			rel.setCreateTime(new Timestamp(System.currentTimeMillis()));
			count += coursepackageVideoTypeRelDao.insertSelective(rel);
		}
		return count;
	}
	
	public int insertByVideoIds(List<Integer> videoIds, int coursepackageId){
		int count = 0;
		for (Integer videoId : videoIds) {
			CoursePackageVideoRel rel = new CoursePackageVideoRel();
			rel.setCoursePackageId(coursepackageId);
			rel.setVideoId(videoId);
			rel.setCreateTime(new Timestamp(System.currentTimeMillis()));
			rel.setSort(100); //暂默认100
			count += coursePackageVideoRelDao.insert(rel);
		}
		return count;
	}

	@Override
	public Object exportExl(CoursePackageInfoDTO info, HttpServletResponse response,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		if (StringUtils.isNotBlank(info.getCoursePackageName())) {
			info.setCoursePackageName(info.getCoursePackageName());
		}
		List<CoursePackageInfoDTO> dataset = coursePackageInfoDao.selectPageByCoursePackageTypeForBack(info);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		String desc = "";
		String reg = "</?[^<]+>";
		//将课程包简介中的html标签过滤掉
		for (CoursePackageInfoDTO coursePackageInfoDTO : dataset) {
			if (StringUtils.isNotBlank(coursePackageInfoDTO.getCoursePackageDesc())) {
				desc = coursePackageInfoDTO.getCoursePackageDesc().replaceAll(reg, "");
				coursePackageInfoDTO.setCoursePackageDesc(desc);
			}
		}
		try {
			ExcelUtil.writeExcel(response, "课程包"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, CoursePackageInfoDTO.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

	@Override
	public Object queryByVideoType(CoursePackageInfoDTO info) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtils.isBlank(info.getVideoTypeId())||info.getUserId()==null
				||info.getDynamicFlag()==null) {
			map.put("err_code", 400);
			map.put("err_msg", "参数异常");
			return map;
		}
		/*
		 *  1--是vip
			2--购买了课程包
			3--不是vip,没购买课程包,有点击历史
			4--三无用户(不是VIP,没购买课程包,无点击历史)
			5--从智慧树页面点击果实(爱心)进来的      微信1.5.2
		 */
		List<CoursePackageInfoDTO> list = null;
		if (info.getDynamicFlag()==1||info.getDynamicFlag()==2||info.getDynamicFlag()==5) {
			list = coursePackageInfoDao.queryByVideoType(info);
			if (info.getDynamicFlag()==5) {
				//用户观看某标签下课程包里视频数量所占该标签下课程包总视频数量的比例(完成度)     微信1.5.2
				double completion = coursePackageInfoDao.queryCompletionByVideoType(info);
				map.put("completion", completion);
			}
		}
		if (info.getDynamicFlag()==3||info.getDynamicFlag()==4) {
			list = coursePackageInfoDao.queryByVideoType2(info);
		}
		//去掉课程包简介中的html标签
		String desc = "";
		String reg = "</?[^<]+>";
		for (CoursePackageInfoDTO coursePackageInfoDTO : list) {
			if (StringUtils.isNotBlank(coursePackageInfoDTO.getCoursePackageDesc())) {
				desc = coursePackageInfoDTO.getCoursePackageDesc().replaceAll(reg, "");
				coursePackageInfoDTO.setCoursePackageDesc(desc);
			}
		}
		if (list!=null && list.size()>0) {
			map.put("err_code", 0);
			map.put("err_msg", "查询有数据");
			map.put("rows", list);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "查询无数据");
		}
		return map;
	}

	@Override
	public Object queryStageTabInfo() {
		Map<String ,Object> map = new HashMap<String, Object>();
		List<Object> list = coursePackageInfoDao.queryStageTabInfo();
		map.put("rows", list);
		return map;
	}

    @Override
    public Object queryCourseByCustomModuleId(CoursePackageInfoDTO coursePackageInfoDTO) {
        Map<String, Object> map = new HashMap<String, Object>();

        List<CoursePackageInfoDTO> list = coursePackageInfoDao.queryCourseByCustomModuleId(coursePackageInfoDTO);
        if (list != null && list.size() > 0) {
            map.put("err_code", 200);
            map.put("err_msg", "查询有数据");
            map.put("rows", list);
        } else {
            map.put("err_code", 500);
            map.put("err_msg", "查询没有数据");
            map.put("rows", list);
        }
        return map;
    }

	@Override
	public Object queryBelongSpecialCP(Integer videoId) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (null == videoId) {
			map.put("err_code", 400);
            map.put("err_msg", "参数异常");
            return map;
		}
		VideoInfo videoInfo = (VideoInfo) videoInfoDao.queryById(videoId);
		if (null == videoInfo) {
			map.put("err_code", 401);
            map.put("err_msg", "未查询到该微课信息");
            return map;
		}
		if ("0".equals(videoInfo.getIsSpecial())) {
			map.put("err_code", 402);
            map.put("err_msg", "该微课不属于特价微课");
            return map;
		}else if ("1".equals(videoInfo.getIsSpecial())) {
			CoursePackageInfo coursePackageInfo = coursePackageInfoDao.queryBelongSpecialCP(videoId);
			if (null == coursePackageInfo) {
				map.put("err_code", 403);
	            map.put("err_msg", "未查询到该微课所属特价课程包信息");
			}else {
				map.put("err_code", 200);
	            map.put("err_msg", "查询成功");
			}
			map.put("coursePackageInfo", coursePackageInfo);
			return map;
		}
		map.put("err_code", -1);
        map.put("err_msg", "查询失败");
		return map;
	}
	@Override
	public Object queryPageByType(String types,Integer page, Integer rows, HttpSession session) {
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			return ResultUtil.error(ResultEnum.NOT_LOGIN);
		}
		if (null == types) {
			return ResultUtil.error(ResultEnum.PARAM_ERROR);
		}
		PageHelper.startPage(page, rows);
		List<CourseDTO> courseList = coursePackageInfoDao.queryPageByType(types, loginUser.getId());
		PageInfo<CourseDTO> pageInfo = new PageInfo<>(courseList);
		//封装结果集
		RelatedCourseDTO result = new RelatedCourseDTO();
		result.setCourseList(courseList);
		result.setTotalRecords(new Integer(String.valueOf(pageInfo.getTotal())));
		return ResultUtil.success(result);
	}

    @Override
    public Object selectUnFinishVideoListById(CoursePackageInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<CoursePackageInfoDTO> list = coursePackageInfoDao.selectUnFinishVideoListById(info);

        for (CoursePackageInfoDTO coursePackageInfoDTO : list) {
            //MP3
            if (StringUtils.isNotBlank(coursePackageInfoDTO.getAudioCode())) {
                PolyInfo cache = RedisUtil.cache(coursePackageInfoDTO.getVideoId() + "");
                coursePackageInfoDTO.setMp3(cache.getMp3());
            }

            //会员那层免费的，后端不判断
            if (coursePackageInfoDTO.getFreeFlag() == 0) {
                Boolean videoVip = RedisUtil.isVideoVip(info.getUserId(), coursePackageInfoDTO.getVideoId());
                if (videoVip) {
                    coursePackageInfoDTO.setIsVipStatus(true);
                } else {
                    coursePackageInfoDTO.setIsVipStatus(false);
                }
            } else {
                coursePackageInfoDTO.setIsVipStatus(false);
            }
        }

        if (null != list && list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功,有数据");
            map.put("rows", list);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "查询成功，无数据");
            map.put("rows", list);
        }
        return map;
    }

}
